export default {
    namespaced: true,
    state() {
        return {
            list: JSON.parse(localStorage.getItem('todolist') || '[]'),
            taskname: '',
            isSel: 'all'
        }
    },
    mutations: {
        add(state, taskname) {
            if (taskname.length === 0) return alert('请输入任务名称!')
                // 将 taskname 传递给父组件
            let id = state.list.length > 0 ? state.list[state.list.length - 1].id + 1 : 100
                // 将子组件传递过来的任务添加至 list 中
            state.list.push({
                id,
                name: taskname,
                isDone: false
            })
        },
        del(state, id) {
            const index = state.list.findIndex(item => item.id === id)
            state.list.splice(index, 1)
        },
        changeSel(state, isSel) {
            state.isSel = isSel
        },
        changeAll(state) {
            state.isSel = 'all'
        },
        changeNo(state) {
            state.isSel = 'no'
        },
        changeYes(state) {
            state.isSel = 'yes'
        },
        clearDone(state) {

            let newArr = []
            state.list.forEach((item, index) => {
                if (!item.isDone) {
                    newArr.push(item)
                }
            })
            state.list = newArr
        },
        setAll(state, val) {
            state.list.forEach(item => item.isDone = val)
        },
        checkLitter(state, { suoyin, value }) {
            console.log(value);
            state.list[suoyin].isDone = value
        },


    },
    getters: {

        showList(state) {
            // 根据当前最新的状态来对 list 进行筛选  
            if (state.isSel === 'yes') {
                let newArr = []
                state.list.forEach(item => {
                    if (item.isDone) {
                        newArr.push(item)
                    }
                })
                return newArr
            } else if (state.isSel === 'no') {
                let newArr = []
                state.list.forEach(item => {
                    if (!item.isDone) {
                        newArr.push(item)
                    }
                })
                return newArr
            } else {
                return state.list
            }
        }
    }
}